package com.cto.uaa.log;

import com.common.log.config.MDCTraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 生成日志链路追踪id，并传入header中
 * //todo GlobalFilter是gateway的过滤器，和security的不同
        **import org.springframework.cloud.gateway.filter.GlobalFilter;
 *    链路追踪id+spanId(每次调用会+1)--> traceId_1,traceId_2,traceId_3,
 */
@Component
@Slf4j
public class LogTraceFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //链路追踪id+spanId(每次调用会+1)--> traceId_1,traceId_2,traceId_3,
        MDCTraceUtils.addTrace();
        //经过测试：在此处打印日志是可以拿到traceId的，证明只要在MDC中put即可在logback文件中读出
        //[1547176840395681792-0]
        //[gateway-service:10.10.5.136:1234] 2022-07-13 19:11:18.562 ERROR 27772 [1547176840395681792-0] [http-nio-1234-exec-1] com.cto.uaa.log.LogTraceFilter           xxxxxxxxxxxxxxxxxxx
        //todo但是在user-server微服务却不行，会不会是feign没有传递这个数据？
        log.error("xxxxxxxxxxxxxxxxxxx");
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(h -> {
                    h.add(MDCTraceUtils.TRACE_ID_HEADER, MDCTraceUtils.getTraceId());
                    h.add(MDCTraceUtils.SPAN_ID_HEADER, MDCTraceUtils.getNextSpanId());
                })
                .build();

        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
